///////////////////////////////////////////////////////////////////////////////
//-----------------------------------------------------------------------------
#include <Model/MeshManager.h>
#include <Model/Mesh.h>
#include <File/LocalFile.h>
#include <Scene/IObjectLoader.h>

//-----------------------------------------------------------------------------

MeshManager::MeshManager()
{
}

//-----------------------------------------------------------------------------

MeshManager::~MeshManager()
{
	ReleaseMeshes();
}

//-----------------------------------------------------------------------------

void		MeshManager::ReleaseMeshes()
{
	std::vector<MeshData*>::iterator it = m_meshes.begin();
	for( ; it != m_meshes.end(); it++ )
	{
		SAFE_DEL( *it );
	}
	m_meshes.clear();
}

//-----------------------------------------------------------------------------

void		MeshManager::AddMesh( MeshData* mesh )
{
	std::vector<MeshData*>::iterator it = m_meshes.begin();
	for( ; it != m_meshes.end(); it++ )
	{
		if( (*it) == mesh || (*it)->IsThisMesh( mesh->GetName() ) )
		{
			DEBUG_ERR( "[MeshManager::AddMesh] Mesh '%s' already in manager!", mesh->GetName().c_str() );
			return;
		}
	}
	m_meshes.push_back( mesh );
}


//-----------------------------------------------------------------------------

bool		MeshManager::IsMeshLoaded( std::string name )
{
	std::vector<MeshData*>::iterator it = m_meshes.begin();
	for( ; it != m_meshes.end(); it++ )
	{
		if( (*it)->IsThisMesh( name ) )
		{
			return true;
		}
	}
	return false;
}

//-----------------------------------------------------------------------------

MeshData*	MeshManager::GetMesh( std::string name )
{
	std::vector<MeshData*>::iterator it = m_meshes.begin();
	for( ; it != m_meshes.end(); it++ )
	{
		if( (*it)->IsThisMesh( name ) )
		{
			return *it;
		}
	}

	MeshData* mesh = NULL;
	LocalFile *file = MGL_NEW LocalFile( name.c_str() );
	if( file->IsOpen() )
	{
		IObjectLoader *loader = IObjectLoader::GetLoaderForFile( file );
		if( loader->Load( file ) )
		{
			mesh = GetMesh( name );
		}
	}
	SAFE_DEL( file );

	return mesh;
}

//-----------------------------------------------------------------------------
///////////////////////////////////////////////////////////////////////////////
